package com.zhangyu.shadow.core.util.timer;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;

/**
 * @author zhangyu
 * @date 2017/10/24
 */

public class TimerUtil {
    private Disposable mDisposable;

    /**
     * 倒计时
     *
     * @param time     倒计时次数
     * @param listener 回调
     */
    public void startTimer(final int time, final ITimerListener listener) {
        Observable.interval(0, 1000, TimeUnit.MILLISECONDS)
                .take(time + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) throws Exception {
                        return time - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull Long aLong) {
                        if (listener != null) {
                            listener.onTimer(aLong);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (mDisposable != null) {
                            mDisposable.dispose();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (listener != null) {
                            listener.onComplete();
                        }
                        if (mDisposable != null) {
                            mDisposable.dispose();
                        }
                    }
                });
    }

    /**
     * 结束倒计时
     */
    public void cancel() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }
}
